package com.gl.admin.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.gl.admin.entity.SysUser;
import com.gl.admin.exception.ServiceException;
import com.gl.admin.service.SysUserService;
import com.gl.admin.common.HttpsStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;

    // 重写preHandle方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        //如果token 是空的直接退出登录
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(HttpsStatus.CODE_401, "token验证失败");
        }
        //定义用户id
        String userId;
        try {
            //如果token 不是空的就空token字符串中获取用户id
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            // 如果获取失败，token不存在
            throw new ServiceException(HttpsStatus.CODE_401, "token验证失败，请重新登录");
        }
        //如果token存在并且获取了用户id 然后查询数据库
        SysUser sysUser = sysUserService.getById(userId);
        //用户是空的 不存在当前用户
        if (sysUser == null) {
            throw new ServiceException(HttpsStatus.CODE_401, "用户不存在，请重新登录");
        }
        //如果用户存在就对用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sysUser.getPassword())).build();
        try {
            //验证token 是否正确
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            // 验证token失败
            throw new ServiceException(HttpsStatus.CODE_401, "令牌验证失败，请重新登录");
        }
        return true;
    }
}
